package com.github.luoshu.open.shiro;

import java.io.*;

/**
 * @author inme
 */
public class ObjectUtils {

    public static byte[] serialize(Object obj) {
        if(obj == null){
            return null;
        }
        if(obj instanceof byte[]){
            return (byte[]) obj;
        }
        if(!(obj instanceof Serializable)){
            throw new RuntimeException(obj.getClass().getName() + " not impl Serializable");
        }
        try(ByteArrayOutputStream bout = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bout)){

            out.writeObject(obj);

            return bout.toByteArray();

        } catch (IOException e) {
            throw new RuntimeException(e.getMessage() , e);
        }
    }

    public static <T> T deserialize(byte[] bytes){
        if(bytes == null){
            return null;
        }
        try(ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
            ObjectInputStream in = new ObjectInputStream(bin)){

            return (T) in.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage() , e);
        }

    }

}
